# 1.按照要求，完成mnist手写识别数据的处理（每题10分）
import tensorflow as tf
from keras.datasets import mnist
import numpy as np
from keras import utils, Sequential, losses, optimizers
from keras.layers import Dense, Dropout

# (1)数据处理
# ①加载数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape)
print(y_train.shape)
# ②对数据进行维度转化
x_train = x_train.reshape(x_train.shape[0], -1)
x_test = x_test.reshape(x_test.shape[0], -1)
# ③数据进行归一化处理
x_train = x_train / 255
x_test = x_test / 255
# ④将y标签进行独热处理
onehot_dim = len(set(y_train))
y_train = utils.to_categorical(y_train, onehot_dim)
y_test = utils.to_categorical(y_test, onehot_dim)

# (2)模型处理
# ①创建模型
# ②创建4层神经网络，每层设置神经元数量为256
# ③每一层都是用relu进行激活
# ④每层都使用dropout处理，失活0.3
model = Sequential(
    [Dense(units=256, activation='relu'),
     Dropout(0.3),
     Dense(units=256, activation='relu'),
     Dropout(0.3),
     Dense(units=256, activation='relu'),
     Dropout(0.3),
     Dense(units=onehot_dim, activation='softmax')]
)
model.compile(optimizer=optimizers.Adam(), loss=losses.categorical_crossentropy, metrics=['acc'])
# ⑤拟合数据进行计算
history = model.fit(x=x_train, y=y_train, epochs=5, batch_size=100, validation_data=(x_test, y_test))
# ⑥打印模型得分
model.evaluate(x_test, y_test)
